<?php
/*
 * @Author: LiuHaiL 18655112670@139.com
 * @Date: 2021-12-17 11:29:08
 * @LastEditors: LiuHaiL 18655112670@139.com
 * @LastEditTime: 2022-11-10 08:35:52
 * @FilePath: \bbsd:\laragon\www\ghpt_api\app\api\model\v1\Learn.php
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
declare (strict_types = 1);

namespace app\api\model\v1;

use think\Model;

/**
 * @mixin \think\Model
 */
class Learn extends AppModel
{
    //

    const TYPE_ONE = 1;
    const TYPE_TWO = 2;

    public static $is_type = array(
        self::TYPE_ONE => '常规',
        self::TYPE_TWO=>'考试',
    );

    //题目
    public function topic(){
        return $this->hasMany(LearnTopic::class,'learn_id');
    }
    //选项
    public function option(){
        return $this->hasMany(LearnOption::class,'learn_id');
    }

    public function admin(){
        return $this->belongsTo(Admins::class,'create_id')->field('id,nickname');
    }


    public static function saveImportExcel($arrData,$uid,$type){
        if (empty($arrData)) {
            $result = 500;
        }else{
            foreach ($arrData as $key=>$value){
               $learn_id = self::create([
                    'title'=>$value['title'],
                    'create_id'=>$uid,
                    'type'=>$type
                ])->id;
                if (isset($value['item'])) { //判断是否包含item字段
                    //如果包含item字段 循环
                    foreach ($value['item'] as $child_key => $child_value) {
                            $learn_topic_id = LearnTopic::create([
                                'topic_title'=>$child_value['topic_title'], //标题
                                'learn_id'=>$learn_id, //id
                                'learn_answer'=>$child_value['learn_answer'],
                                'question_type'=>$child_value['question_type'],
                                'score'=>$child_value['score'],
                                'answer_explain'=>$child_value['answer_explain'],
                                'create_id'=>$uid,
                                'topic_type'=>$type
                            ])->id;
                        if (isset($child_value['item'])) {
                            foreach ($child_value['item'] as $child_child_key => $child_child_value) {
                                LearnOption::create([
                                    'option_title'=>$child_child_value['option_title'], //标题
                                    'learn_id'=>$learn_id, //id
                                    'learn_topic_id'=>$learn_topic_id,
                                    'create_id'=>$uid
                                ]);
                            }
                        }
                    }
                }
            }
            $result = 200;
        }
        return $result;
    }
}
